package com.wwcom.darteagle;

import android.app.Activity;
import android.util.Log;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.wwcom.darteagle.data.DartEagleDatabase;
import com.wwcom.darteagle.fragment.StatsDetailsFragment;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.Score;
import com.wwcom.darteagle.util.Messages;
import com.wwcom.darteagle.util.Posts;
import com.wwcom.darteagle.util.Settings;
import com.wwcom.darteagle.util.Tips;
import com.wwcom.darteagle.view.LegHistoryView;
import com.wwcom.darteagle.view.ScoreMatrixView;

public class MatchActivity extends Activity {
	private static final int DIALOG_NONE = 0;
	private static final int DIALOG_LEG_COMPLETE = 1;
	private static final int DIALOG_SET_COMPLETE = 2;
	private static final int DIALOG_MATCH_COMPLETE = 3;
	private static final int DIALOG_GOOD_SCORE = 4;
	private static final int DIALOG_EDIT_SCORE_TIPS= 5;
	private static final int DIALOG_MATCH_STATS_TIPS= 6;
	private static final int BROADCAST_MATCH_UPDATE_FINALISED = 0;
	private static final int BROADCAST_MATCH_UPDATE_NEWLEG = 1;
	
	private boolean saveToDatabase;
	private static final String SHOWING_DIALOG= "showingDialog";
	private static final String DIALOG_EXTRAS= "dialogExtras";
	private int showingDialog;
	private Bundle dialogExtras;
	private Dialog currentDialog;
		
	private View contextMenuView;
		
	GlobalAppData gd= GlobalAppData.getSingletonInstance();
	
	//broadcast management
    LocalBroadcastManager mLocalBroadcastManager;	
    BroadcastReceiver mReceiver;
	
    /** Called when the activity is first created. */	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setTheme(Settings.getThemeID(this));    	

    	Log.d("MatchActivity","onCreate");        
        
		//load match if it was null
		if (gd.match == null) {
			DartEagleDatabase db= new DartEagleDatabase(this);             	    	
			gd.match= db.getResumableMatch();
			db.close();
		}        
        
        //layout
        setContentView(R.layout.match);

    	// We use this to send broadcasts within our local process.
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        final LegHistoryView lhv= (LegHistoryView)findViewById(R.id.legHistoryView);
        
        //broadcast receivers
        showingDialog= DIALOG_NONE;
        dialogExtras= null;
        currentDialog= null;
	    IntentFilter filter = new IntentFilter();
	    filter.addAction(Messages.MATCH_UPDATE_FINALISED);
	    filter.addAction(Messages.MATCH_NEWLEG);
	    filter.addAction(Messages.MATCH_LEGCOMPLETE);
	    filter.addAction(Messages.MATCH_SETCOMPLETE);
	    filter.addAction(Messages.MATCH_MATCHCOMPLETE);
   	    filter.addAction(Messages.GOODSCORE);
	    filter.addAction(Messages.SHOWTIPS_EDITSCORE);
	    filter.addAction(Messages.SHOWTIPS_MATCHSTATS);
	    mReceiver= new BroadcastReceiver() {
			 @Override
			 public void onReceive(Context arg0, Intent arg1) {
				if (arg1.getAction().equals(Messages.MATCH_UPDATE_FINALISED)) {
			        if (lhv != null) lhv.updateVisitScoreList(); 
			        ((ScoreMatrixView)findViewById(R.id.score_matrix_view)).updateView();
			        updateCurrentPlayerString();
				} else if (arg1.getAction().equals(Messages.MATCH_NEWLEG)) {
					if (lhv != null) lhv.newVisitScoreList();
			        ((ScoreMatrixView)findViewById(R.id.score_matrix_view)).newLeg();					 
			        updateCurrentPlayerString();
				} else if (arg1.getAction().equals(Messages.MATCH_LEGCOMPLETE)) {
					showDialog(DIALOG_LEG_COMPLETE, arg1.getExtras());
			        updateCurrentPlayerString();
				} else if (arg1.getAction().equals(Messages.MATCH_SETCOMPLETE)) {
					showDialog(DIALOG_SET_COMPLETE, arg1.getExtras());
			        updateCurrentPlayerString();
				} else if (arg1.getAction().equals(Messages.MATCH_MATCHCOMPLETE)) {
			        ((ScoreMatrixView)findViewById(R.id.score_matrix_view)).updateView();					 
					showDialog(DIALOG_MATCH_COMPLETE, arg1.getExtras());
			        updateCurrentPlayerString();
				} else if (arg1.getAction().equals(Messages.GOODSCORE)) {
					showDialog(DIALOG_GOOD_SCORE, arg1.getExtras());
			        updateCurrentPlayerString();
				} else if (arg1.getAction().equals(Messages.SHOWTIPS_EDITSCORE)) {
					showDialog(DIALOG_EDIT_SCORE_TIPS, arg1.getExtras());
				} else if (arg1.getAction().equals(Messages.SHOWTIPS_MATCHSTATS)) {
					showDialog(DIALOG_MATCH_STATS_TIPS, arg1.getExtras());
				}
			 }
		 }; 
		 mLocalBroadcastManager.registerReceiver(mReceiver, filter);					   

		// try to restore any dialog that was showing if we changed configuration
		 Bundle lastConfig= (Bundle)getLastNonConfigurationInstance();
		if (lastConfig != null) {
			showingDialog = lastConfig.getInt(SHOWING_DIALOG);
			if (showingDialog != DIALOG_NONE) {
				final Bundle extras = lastConfig.getBundle(DIALOG_EXTRAS);
				showDialog(showingDialog, extras);
			}
		}
		 
		 updateCurrentPlayerString();
		 saveToDatabase= false;
    }
    
    @Override 
    public Object onRetainNonConfigurationInstance () {
    	//we have to use this method and not onSaveInstanceState because it gets called between onStop and onDestroy,
    	// saveInstanceState gets called too early because we may get messages to display dialogs after onPause    	
    	Log.d("MatchActivity","onRetainNonConfigurationInstance");     
    	Bundle outState= new Bundle();
    	outState.putInt(SHOWING_DIALOG, showingDialog);  
    	outState.putBundle(DIALOG_EXTRAS, dialogExtras);    	
    	return (Object)outState;
    }
    
    
    @Override
    public void onBackPressed() {
    	saveToDatabase= true;
    	super.onBackPressed();
    }
        
    @Override
	protected void onPause() {
	    super.onPause();
    	Log.d("MatchActivity","onPause");	   	
      	if (saveToDatabase) {
	    	if (!gd.match.isMatchComplete()) {
	    		Toast t = Toast.makeText(this, getString(R.string.match_saved_resume), Toast.LENGTH_SHORT);
	    		t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
	    		t.show();
	    	} else {
	    		Toast t = Toast.makeText(this, getString(R.string.match_saved_stats), Toast.LENGTH_SHORT);
	    		t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
	    		t.show();    		
	    	}
	    }
	    if (currentDialog != null) {
	    	currentDialog.dismiss();
	    	currentDialog= null;
	    }
	 }
	 
    @Override
    protected void onDestroy() {
        super.onDestroy();
    	Log.d("MatchActivity","onDestroy");	   	
    	//unregister listeners
    	mLocalBroadcastManager.unregisterReceiver(mReceiver);    	

    	if (currentDialog != null) {
	    	currentDialog.dismiss();
	    	currentDialog= null;
	    }

        //update match into database
    	DartEagleDatabase db= new DartEagleDatabase(this);             	
	    db.deleteAllResumableMatches();
	    db.insertMatch(gd.match);
	   	db.close();
	   	

    }
        
    // Listeners
    public void onClickEnterScore(View v) {
    	Intent i= new Intent(this,ScoreEntryActivity.class);
    	startActivity(i);
    }
    
    public void onClickBustScore(View v) {
    	Score score = new Score();
    	int[] dartScores= { 0,0,0 };
    	boolean[] isDouble= { false,false,false };
    	boolean[] isTreble= { false,false,false };
    	score.setDartScore( dartScores );
    	score.setIsDouble( isDouble );
    	score.setIsTreble( isTreble );
    	gd.match.updateCurrentPlayerScore(score);
    	gd.match.nextPlayer();
    	broadcastUpdated(BROADCAST_MATCH_UPDATE_FINALISED);    	
    }            
    
    //broadcasters
	private void broadcastUpdated(int id) {
		Intent intent=new Intent();
		switch(id) {
		case BROADCAST_MATCH_UPDATE_FINALISED:
			intent.setAction(Messages.MATCH_UPDATE_FINALISED);
			break;
		case BROADCAST_MATCH_UPDATE_NEWLEG:
			intent.setAction(Messages.MATCH_NEWLEG);
			break;
		}
		mLocalBroadcastManager.sendBroadcast(intent);
	}

	//current player string
	private void updateCurrentPlayerString() {
        MatchPlayer currentPlayer= gd.match.getCurrentPlayer();
        String playerName= currentPlayer.getPlayer().getName();
		TextView tv= (TextView)findViewById(R.id.currentPlayerStr);
		tv.setText(Html.fromHtml("<b>" + playerName.toUpperCase() + "</b> "+getString(R.string.match_to_throw_next)));        
	}
	
		
	//dialogs 
    @Override	
	protected Dialog onCreateDialog(int id, final Bundle extras) {
    	final Activity context= this;
    	showingDialog= id;
    	dialogExtras= extras;
		LayoutInflater inflator = ((Activity) context).getLayoutInflater();
        switch (id) {
        case DIALOG_LEG_COMPLETE:
        	View view = inflator.inflate(R.layout.dialog_template_twobuttons, null);
        	((TextView)view.findViewById(R.id.message)).setText(
        			Html.fromHtml(String.format(getString(R.string.match_dialog_leg_won),
        					gd.match.getLegWinner().getPlayer().getName(),
        					gd.match.getNextLegStartPlayer().getPlayer().getName())));

        	Dialog d= new AlertDialog.Builder(this)
        	.setTitle(getString(R.string.match_dialog_leg_won_title,gd.match.getLegWinner().getPlayer().getName()))
        	.setIcon(R.drawable.ic_dialog_eagle)
        	.setView(view)
        	.setCancelable(true)
        	.setOnCancelListener(new DialogInterface.OnCancelListener() {
        		public void onCancel(DialogInterface dialog) {
        			gd.match.nextLeg();
        			showingDialog= DIALOG_NONE;
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        		};
        	})
        	.create();
        	final Dialog dRef1= d;
        	Button b= ((Button)view.findViewById(R.id.positiveButton));
        	b.setText(getString(R.string.match_dialog_game_on));
        	b.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View button) {
        			gd.match.nextLeg();
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        			showingDialog= DIALOG_NONE;
        			dRef1.dismiss();
        		}
        	});
        	b= ((Button)view.findViewById(R.id.negativeButton));
        	b.setText(getString(R.string.match_dialog_leg_stats));
        	b.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View button) {
        			Intent i= new Intent(context,MatchStatsActivity.class);
        			i.putExtra(StatsDetailsFragment.MATCH_ID, (long)-1);
        			i.putExtra(StatsDetailsFragment.LEG_IND, gd.match.getLegNumber());
        			i.putExtra(StatsDetailsFragment.SET_IND, gd.match.getSetNumber());
        			startActivity(i);        				
        			gd.match.nextLeg();        			
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        			showingDialog= DIALOG_NONE;
        			dRef1.dismiss();
        		}
        	});
			view.findViewById(R.id.tweetButton).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
        			gd.match.nextLeg();
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
                    Intent i = new Intent(MatchActivity.this,TwitterActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    i.putExtra("message", Posts.legComplete(Posts.TWITTER,extras));
                    startActivity(i);   
                }
			});
        	d.show();
        	currentDialog= d;
            break;
        case DIALOG_SET_COMPLETE:
        	view = inflator.inflate(R.layout.dialog_template_twobuttons, null);
        	((TextView)view.findViewById(R.id.message)).setText(
        			Html.fromHtml(String.format(getString(R.string.match_dialog_set_won),
        					gd.match.getLegWinner().getPlayer().getName(),
        					gd.match.getNextSetStartPlayer().getPlayer().getName())));

        	d= new AlertDialog.Builder(this)
        	.setTitle(getString(R.string.match_dialog_set_won_title,gd.match.getLegWinner().getPlayer().getName()))
        	.setIcon(R.drawable.ic_dialog_eagle)
        	.setView(view)
        	.setCancelable(true)
        	.setOnCancelListener(new DialogInterface.OnCancelListener() {
        		public void onCancel(DialogInterface dialog) {
        			gd.match.nextSet();
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        			showingDialog= DIALOG_NONE;
        		};
        	})
        	.create();
        	final Dialog dRef2= d;
        	b= ((Button)view.findViewById(R.id.positiveButton));
        	b.setText(getString(R.string.match_dialog_game_on));
        	b.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View button) {
        			gd.match.nextSet();
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        			showingDialog= DIALOG_NONE;
        			dRef2.dismiss();
        		}
        	});
        	b= ((Button)view.findViewById(R.id.negativeButton));
        	b.setText(getString(R.string.match_dialog_set_stats));
        	b.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View button) {
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        			Intent i= new Intent(context,MatchStatsActivity.class);
        			i.putExtra(StatsDetailsFragment.MATCH_ID, (long)-1);
        			i.putExtra(StatsDetailsFragment.LEG_IND, -1);
        			i.putExtra(StatsDetailsFragment.SET_IND, gd.match.getSetNumber());
        			Log.d("MatchActivity","setInd: "+gd.match.getSetNumber());
        			startActivity(i);        				
        			gd.match.nextSet();
        			showingDialog= DIALOG_NONE;
        			dRef2.dismiss();
        		}
        	});
        	view.findViewById(R.id.tweetButton).setOnClickListener(
        			new View.OnClickListener() {
        		public void onClick(View v) {
        			Intent i = new Intent(MatchActivity.this,TwitterActivity.class);
        			i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        			i.putExtra("message", Posts.setComplete(Posts.TWITTER,extras));
        			startActivity(i);   
        			gd.match.nextSet();
        			broadcastUpdated(BROADCAST_MATCH_UPDATE_NEWLEG);
        		}
        	});
        	d.show();
        	currentDialog= d;
            break;
        case DIALOG_MATCH_COMPLETE:
        	view = inflator.inflate(R.layout.dialog_template_onebutton, null);
        	((TextView)view.findViewById(R.id.message)).setText(
        			Html.fromHtml(String.format(getString(R.string.match_dialog_match_won),
        					gd.match.getLegWinner().getPlayer().getName())));
            d= new AlertDialog.Builder(this)
                .setTitle(getString(R.string.match_dialog_match_won_title,gd.match.getLegWinner().getPlayer().getName()))
                .setIcon(R.drawable.ic_dialog_eagle)
        	.setView(view)
        	.setCancelable(true)
        	.setOnCancelListener(new DialogInterface.OnCancelListener() {
        		public void onCancel(DialogInterface dialog) {
        	    	saveToDatabase= true;
        			showingDialog= DIALOG_NONE;
        			finish();
        		};
        	})
        	  .create();
        	final Dialog dRef3= d;
        	b= ((Button)view.findViewById(R.id.positiveButton));
        	b.setText(getString(R.string.match_dialog_match_stats));
        	b.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View button) {
        			Intent i= new Intent(context,MatchStatsActivity.class);
        			startActivity(i);        				
        			dRef3.dismiss();
        	    	saveToDatabase= true;
        			showingDialog= DIALOG_NONE;
        			finish();
        		}
        	});
        	view.findViewById(R.id.tweetButton).setOnClickListener(new View.OnClickListener() {
        		public void onClick(View v) {
        			Intent i = new Intent(MatchActivity.this,TwitterActivity.class);
        			i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        			i.putExtra("message", Posts.matchComplete(Posts.TWITTER,extras));
        			startActivity(i);   
        		}
        	});
            d.show();
        	currentDialog= d;
            break;

        case DIALOG_GOOD_SCORE:        	
    		view = inflator.inflate(R.layout.dialog_template_onebutton_optout, null);
        	((TextView)view.findViewById(R.id.message)).setText(getString(R.string.match_dialog_great_shot_title));
            d= new AlertDialog.Builder(this)
                .setTitle(getString(R.string.match_dialog_great_shot,extras.getInt("score")))
                .setIcon(R.drawable.ic_dialog_eagle)
                .setCancelable(true)                
                .setView(view).create();
                            
            final Dialog dRef= d;            
            d.setOnCancelListener(new DialogInterface.OnCancelListener() {
                	public void onCancel(DialogInterface dialog) {
                		optOut(dRef,"sharingDialogPrefs");
            			showingDialog= DIALOG_NONE;
                	};
                });
            
        	b= ((Button)view.findViewById(R.id.positiveButton));
        	b.setText(getString(R.string.match_dialog_no_thanks));
        	b.setOnClickListener(new View.OnClickListener() {
        		public void onClick(View button) {
            		optOut(dRef,"sharingDialogPrefs");
        			showingDialog= DIALOG_NONE;
        			dRef.dismiss();
        		}
        	});
			view.findViewById(R.id.tweetButton).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
            		optOut(dRef,"sharingDialogPrefs");
                    Intent i = new Intent(MatchActivity.this,TwitterActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    i.putExtra("message", Posts.goodScore(Posts.TWITTER,extras));
                    startActivity(i);   
        			showingDialog= DIALOG_NONE;
                    dRef.dismiss();
                }
			});
			/*view.findViewById(R.id.faceBookButton).setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
            		optOut(dRef,"sharingDialogPrefs");
                    Intent i = new Intent(MatchActivity.this,FaceBookActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    i.putExtra("message", Posts.goodScore(Posts.FACEBOOK,extras));
                    startActivity(i);   
                    dRef.dismiss();
                }
			});*/
            d.show();
        	currentDialog= d;
            break;
        case DIALOG_EDIT_SCORE_TIPS:   
        	if (showTip(Tips.EDITSCORE)) {
	    		view = inflator.inflate(R.layout.dialog_template_tip, null);
	        	((TextView)view.findViewById(R.id.message)).setText(getString(R.string.match_dialog_tip_edit_scores));
	            d= new AlertDialog.Builder(this)
	                .setTitle(getString(R.string.match_dialog_tip_edit_scores_title))
	                .setIcon(R.drawable.ic_dialog_eagle)
	                .setCancelable(true)
		        	.setOnCancelListener(new DialogInterface.OnCancelListener() {
		        		public void onCancel(DialogInterface dialog) {        			
		    	            tipShown(Tips.EDITSCORE);
		        			showingDialog= DIALOG_NONE;
		        		};
		        	})
	                .setView(view).create();                            
	            d.show();
	        	currentDialog= d;
	            
	            final Dialog dRef4= d;            
	        	b= ((Button)view.findViewById(R.id.positiveButton));
	        	b.setText(getString(R.string.match_dialog_ok));
	        	b.setOnClickListener(new View.OnClickListener() {
	        		public void onClick(View button) {
	        			tipShown(Tips.EDITSCORE);
	        			showingDialog= DIALOG_NONE;
	        			dRef4.dismiss();
	        		}
	        	});
	            
        	}
        	break;
        case DIALOG_MATCH_STATS_TIPS:   
        	if (showTip(Tips.MATCHSTATS)) {
	    		view = inflator.inflate(R.layout.dialog_template_tip, null);
	        	((TextView)view.findViewById(R.id.message)).setText(getString(R.string.match_dialog_tip_match_stats));
	            d= new AlertDialog.Builder(this)
	                .setTitle(getString(R.string.match_dialog_tip_match_stats_title))
	                .setIcon(R.drawable.ic_dialog_eagle)
	                .setCancelable(true)
		        	.setOnCancelListener(new DialogInterface.OnCancelListener() {
		        		public void onCancel(DialogInterface dialog) {        			
		    	            tipShown(Tips.MATCHSTATS);
		        			showingDialog= DIALOG_NONE;
		        		};
		        	})
	                .setView(view).create();                            
	            d.show();
	        	currentDialog= d;
	            
	            final Dialog dRef5= d;            
	        	b= ((Button)view.findViewById(R.id.positiveButton));
	        	b.setText(getString(R.string.match_dialog_ok));
	        	b.setOnClickListener(new View.OnClickListener() {
	        		public void onClick(View button) {
	        			tipShown(Tips.MATCHSTATS);
	        			showingDialog= DIALOG_NONE;
	        			dRef5.dismiss();
	        		}
	        	});
	            
        	}
        	break;
        }
        
        return null;        
    }
    
    private void optOut(Dialog dialog, String pref) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		CheckBox optOut= (CheckBox)dialog.findViewById(R.id.opt_out);
		if (optOut.isChecked()) {
	        SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean(pref, false);
	        // Commit the edits!
	        editor.commit(); 			
			Toast t= Toast.makeText(MatchActivity.this, getString(R.string.match_sharing_dialogs_reenabled), Toast.LENGTH_LONG);
			t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
			t.show();
		}
    }
        
    private boolean showTip(String tipName) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		return prefs.getBoolean(tipName, true);    	
    }

    private void tipShown(String tipName) {
		final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        SharedPreferences.Editor editor = prefs.edit();
		editor.putBoolean(tipName, false);
        // Commit the edits!
		editor.commit();
		Toast t= Toast.makeText(MatchActivity.this, getString(R.string.match_sharing_tip_reenabled), Toast.LENGTH_LONG);
		t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
		t.show();
    }
    
    //menus
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.match_options_menu, menu);
        return true;
    }    
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_match_statistics:
        	Intent i= new Intent(this,MatchStatsActivity.class);
        	startActivity(i);
        	return true;
        case R.id.menu_options:
        	i= new Intent(this,OptionsActivity.class);
        	i.putExtra(HomeActivity.RESUME_MATCH, true);
        	startActivity(i);
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    //context menus
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
      if (v.getTag() != null) {
    	  contextMenuView= v;
    	  MenuInflater inflater = getMenuInflater();
    	  inflater.inflate(R.menu.score_edit_context_menu, menu);
      	  if (contextMenuView.getTag() != null) {
      		String title= 
      				((LegHistoryView)findViewById(R.id.legHistoryView))
      				.getContextMenuTitle(contextMenuView.getTag());
    	    MenuItem editItem= menu.getItem(0);
    	    editItem.setTitle("Edit: "+title);
      	  }
      }
    }    
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      switch (item.getItemId()) {
      case R.id.menu_edit_score:
    	if (contextMenuView != null && contextMenuView.getTag() != null) { 
          ((LegHistoryView)findViewById(R.id.legHistoryView)).updateVisitScore(contextMenuView.getTag());
    	}
        return true;
      default:
        return super.onContextItemSelected(item);
      }
    }    
    
	
}